<template>
  <div class="login-form">
    <p class="login-form-logo">账号密码登录</p>
    <el-form :model="loginForm" ref="loginForm" :rules="rules" status-icon label-width="0">
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" prefix-icon="el-icon-user" placeholder="用户名/手机号/邮箱"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          type="password"
          prefix-icon="el-icon-lock"
          placeholder="密码"
          show-password
          v-model="loginForm.password"
        ></el-input>
      </el-form-item>
      <el-form-item prop="captcha">
        <el-input
          v-model="loginForm.captcha"
          placeholder="验证码"
          prefix-icon="el-icon-key"
          autocomplete="off"
          autocapitalize="off"
          spellcheck="false"
          style="float: left; width: 122px;"
        ></el-input>
        <div class="captcha">
          <img
            style="width:150px;height:40px;margin-left:10px;"
            :src="codeURL"
            @click="refreshCode"
          />
        </div>
      </el-form-item>
    </el-form>
    <el-checkbox v-model="remember" class="login-checkbox-remember">记住账号</el-checkbox>
    <el-button
      type="primary"
      class="login-btn-submit"
      :disabled="loading"
      :loading="loading"
      @click="submitForm('loginForm')"
    >登录</el-button>
    <div class="login-form-foot">
      <el-link type="primary" class="login-link-forget" @click="forgetShow">忘记密码?</el-link>
      <el-link type="primary" class="login-link-register" @click="registerShow">立即注册</el-link>
    </div>
  </div>
</template>

<script>
import { userAPI } from "@/utils/api.js";
import { baseUrl } from "@/utils/global.js";
import { mapMutations } from "vuex";
export default {
  data() {
    return {
      loading: false, //点击登录显示加载中,并禁用
      /* 登录表单 */
      loginForm: {
        username: "",
        password: "",
        captcha: "" //输入验证码值
      },
      randomKey: "", ///随机key，用于后台保存验证码
      codeURL: "", //验证码图片地址
      remember: false, //是否记住账号
      //验证规则
      rules: {
        username: [
          { required: true, message: "请输入登录账号", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        captcha: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { min: 4, max: 4, message: "长度限制4个字符", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    //初始获取验证码
    this.refreshCode();
  },
  methods: {
    ...mapMutations(["setUserInfo", "setTry"]), //引入vuex辅助函数，混入methods 同名方法
    forgetShow() {
      //显示忘记密码
      this.$emit("forgetShow");
    },

    registerShow() {
      //实现立即注册
      this.$emit("registerShow");
    },
    refreshCode() {
      //刷新验证码
      this.randomKey = Math.random()
        .toString(36)
        .substr(2, 4);
      this.codeURL = `${baseUrl}/user/getImgToken?randomKey=` + this.randomKey;
    },
    submitForm(formName) {
      /* 提交登录表单 */
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.loading = true;
          let data = this.loginForm;
          data.token = this.randomKey;
          userAPI.login
            .login(data)
            .then(res => {
              //保存refreshToken和token，refreshToken用于刷新token
              localStorage.setItem("refreshToken", res.data.refreshToken);
              localStorage.setItem("token", res.data.token);
              this.setUserInfo(res.data.userInfo); //保存userinfo
              this.setTry(true); //保存是否重新加载的状态
              sessionStorage.removeItem("login_current"); //清除login页表单状态
              this.$router.replace("/home"); //路由跳转
            })
            .catch(err => {
              console.log(err);
            })
            .finally(() => {
              this.refreshCode();
              this.loading = false; //取消加载和禁用
            });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.login-form {
  opacity: 0;
  position: absolute;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
  width: 352px;
  padding: 10px 20px;
  box-shadow: rgba(0, 0, 0, 0.3) 0 0 50px;
  border-radius: 3px;
  background-color: #fff;
  animation: login-show 1s ease 0.2s forwards;
  .login-form-logo {
    padding: 14px 0;
    font-size: 18px;
    font-weight: 600;
    text-align: center;
  }
  .login-btn-submit {
    width: 100%;
    margin: 10px 0;
  }
  .login-form-foot {
    display: flex;
    justify-content: space-between;
  }
}
@keyframes login-show {
  0% {
    opacity: 0;
    right: -100px;
  }
  50% {
    opacity: 0.8;
    right: 20px;
  }
  95% {
    opacity: 0.9;
    right: -5px;
  }
  100% {
    opacity: 1;
    right: 0;
  }
}
</style>